<?php
/**
 * Created by PhpStorm.
 * User: coder
 * Date: 2019/4/11
 * Time: 15:57
 */
namespace logink;
use util\soapHelper;
use logink\cTokenInfo;
use logink\cUsernameToken;

class loginkHelper
{
    private $userId;
    private $password;
    private $toUserId;

    public function __construct()
    {
        $this->userId = config('app.logink.uid');
        $this->password = config('app.logink.pwd');
        $this->toUserId = config('app.logink.touid');
        $this->resourcesId = config('app.logink.resourcesId');
    }

    private function getToken()
    {
        header ( "Content-Type: text/html; charset=utf-8" );
        $ws = config('app.logink.authUrl');
        $client = new \SoapClient ($ws);
        try {
            $data = array(
                'authenticate' => [
                    'applicant' => $this->userId,
                    'userid' => $this->userId,
                    'password' => $this->password,
                    'resource'=>$this->resourcesId, // @todo test env
                ]
            );
            $rsp = $client->__call('authenticate', $data);

        } catch (\SOAPFault $e) {
            throw new \Exception($e->getMessage());
        }

        //token状态的判断和异常处理
        $tokenValied = $rsp->AuthenticationResult->tokenValied;

        if ($tokenValied) {
            return $rsp->AuthenticationResult->token;
        } else {
            throw new \Exception('token获取失败');
        }
    }

    public function exchangeTransport($xmlFile, $actionType,$guid, $filename)
    {
        header ( "Content-Type: text/html; charset=utf-8" );

        $token = $this->getToken();
        $ws = config('app.logink.exUrl');
        $options = [];
        $client = new soapHelper($ws, $options);
        $res = $this->send($client,$this->userId,$token,$this->toUserId, $actionType, $xmlFile, $guid, $filename);
        return $res;
    }

    private function send($client, $userId, $token, $toUserId, $actionType, $xmlFile, $guid, $filename)
    {
        try {
            $header = $this->getSendHeader($userId, $token);
            $data = $this->getSendData($userId, $toUserId, $actionType, $xmlFile, $guid, $filename);
            $httpsUrl = config('app.logink.realExUrl');
            $client->__setLocation($httpsUrl);
            $client->__setSoapHeaders($header);
            $rsp = $client->__soapCall('send', $data);
        } catch (\SOAPFault $e) {
            throw new \Exception($e->getMessage());
        }

        if ($rsp->SendResult) {
            return true;
        } else {
            throw new \Exception('已执行上传任务但是国家检测平台返回失败');
        }
    }

    //设置Header
    private function getSendHeader($userId, $token)
    {
        $ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';
        $userNameVar = new \SoapVar($userId, XSD_STRING, null, $ns, null, $ns);
        $tokenVar = new \SoapVar('ticket:'.$token, XSD_STRING, null, $ns, null, $ns);
        $tokenObj = new cTokenInfo($userNameVar, $tokenVar);
        $securityVar = new \SoapVar($tokenObj, SOAP_ENC_OBJECT, null, $ns, 'UsernameToken', $ns);
        $utObj = new cUsernameToken($securityVar);
        $utVar = new \SoapVar($utObj, SOAP_ENC_OBJECT, null, $ns, 'UsernameToken', $ns);
        return new \SOAPHeader($ns, 'Security', $utVar, false);
    }

    //设置报文体
    private function getSendData($userId, $toUserId = '',$actionType = '', $xmlFile, $guid, $filename)
    {
        $xml = $this->getBase64DataFromFile($xmlFile);
        return [
                    'SendRequest' => [
                    'ToAddress' => $toUserId,
                    'ExchangeEvent' => [
                        'EventID' => $guid,
                        'ActionType' => $actionType,
                        'ExchangeDataPackage' => [
                            'packageID' => $guid,
                            'transactionID' => $guid, // string
                            'createTime'=>date('Y-m-d'), // datetime
                            //'expireTime'=>'2017-04-15', // 永久有效
                            'title' => $actionType,
                            'ExchangeDataPackageUnit' => [
                                'groupID' => '1',
                                'groupSize' => 1,
                                'sequenceInGroup' => 1,
                                'unitID' => '2',
                                'source' => 'ab',
                                'entityIDName' => '123',//anyURI
                                'entityDispName'=>'1',
                                'createDate'=>date('Y-m-d'),//dateTime
                                //'expireDate'=>'2017-04-15',
                                'DataFile' => [
                                    'dataFileID' => '2',//NCName
                                    'fileName' => $filename,
                                    'dataFileFormat' => 'xml',
                                    'Base64EncodedData' => $xml,//base64Binary
                                    'AttachmentData' => '',//base64Binary
                                ],
                            ],
                        ],
                    ],
                ]
            ];

    }

    //Base64处理文件
    private function getBase64DataFromFile($filename)
    {
        $base64Data = base64_encode(file_get_contents($filename));
        return $base64Data;
    }
}
